import javax.swing.tree.TreeNode;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2022-10-05
 * Time: 16:10
 */
public class MyBinaryTree {

    // 二叉树的属性
    static class TreeNode {
        public char val; // 根
        public TreeNode left; // 左树
        public TreeNode right; // 由树

        public TreeNode(char val) {
            this.val = val;
        }
    }

    // 穷举创建一棵树
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        // 连接书
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;
    }

    // 前序遍历
    public void preOrder(TreeNode root) {
        // 没有根
        if (root == null) {
            return;
        }
        //打印根节点
        System.out.print(root.val + " ");
        // 找左树
        preOrder(root.left);
        // 找右树
        preOrder(root.right);
    }

    // 前序遍历迭代
    public List<Character> preorderTraversal(TreeNode root) {
        // 存放节点值的列表
        List<Character> list = new ArrayList<>();
        TreeNode cur = root;
        // 存放节点的栈
        Stack<TreeNode> stack = new Stack<>();
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                list.add(cur.val);
                cur = cur.left;
            }
            TreeNode tmp = stack.pop();
            cur = tmp.right;
        }
        return list;
    }

    // 中序遍历
    public void inOrder(TreeNode root) {
        // 没有根
        if (root == null) {
            return;
        }
        // 找左树
        inOrder(root.left);
        //打印根节点
        System.out.print(root.val + " ");
        // 找右树
        inOrder(root.right);
    }

    // 中序遍历迭代
    public List<Character> inorderTraversal(TreeNode root) {
        // 存放节点值的列表
        List<Character> list = new ArrayList<>();
        TreeNode cur = root;
        // 存放节点的栈
        Stack<TreeNode> stack = new Stack<>();
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            // 为空 弹出栈顶元素
            TreeNode tmp = stack.pop();
            // 添加进顺序表
            list.add(tmp.val);

            cur = tmp.right;
        }
        return list;
    }

    // 后序遍历
    void postOrde(TreeNode root) {
        // 没有根
        if (root == null) {
            return;
        }
        // 找左树
        postOrde(root.left);
        // 找右树
        postOrde(root.right);
        //打印根节点
        System.out.print(root.val + " ");
    }

    // 后续遍历迭代
    public List<Character> postorderTraversal(TreeNode root) {
        List<Character> list = new ArrayList<>();
        TreeNode cur = root;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode tmp = stack.peek();
            if (tmp.right == null || tmp.right == prev) {
                stack.pop();
                list.add(tmp.val);
                prev = tmp;
            } else {
                cur = tmp.right;
            }
        }
        return list;
    }


    // 获取树中节点的个数
    public int size(TreeNode root) {
        if (root == null) {
            return 0;
        }
        // 左树节点 + 右树节点 + 根节点
        return size(root.left) + size(root.right) + 1;
    }

    // 获取叶子节点的个数
    public int getLeafNodeCount(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount(root.left) + getLeafNodeCount(root.right);
    }

    // 子问题思路-求叶子结点个数 //
    // 获取第K层节点的个数
    public int getKLevelNodeCount(TreeNode root, int k) {
        if (k <= 0) {
            throw new KIlligealException("k值输入错误！");
        }
        if (root == null) {
            return 0;
        }
        // K 为 1 的时候正好为 k 那一层. 相对根节点为第 K 层
        if (k == 1) {
            return 1;
        }

        // 左树的下一层和右树的下一层
        return getKLevelNodeCount(root.left, k - 1) + getKLevelNodeCount(root.right, k - 1);
    }

    // 获取二叉树的高度
    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        // 获取根节点左树的高度
        int leftHeight = getHeight(root.left);
        // 获取根节点右树的高度
        int rightHeight = getHeight(root.right);
        //
        return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
    }

    // 检测值为value的元素是否存在
    public TreeNode find(TreeNode root, int key) {
        if (root == null) {
            return null;
        }

        if (root.val == key) {
            return root;
        }

        TreeNode retLeft = find(root.left, key);
        if (retLeft != null) {
            return retLeft;
        }

        TreeNode retRight = find(root.right, key);
        if (retRight != null) {
            return retRight;
        }

        return null;
    }

    // 层序遍历
    public void levelOrder(TreeNode root) {
        // 利用队列先进先出
        Queue<TreeNode> queue = new LinkedList<>();
        // 将没有给节点都存到队列中
        if (root == null) {
            return;
        } else {
            queue.offer(root);
        }
        while (!queue.isEmpty()) {
            // 记录当前队顶元素访问该队顶元素的左右树
            TreeNode front = queue.poll();
            // 出当前队顶元素
            System.out.print(front.val + " ");
            if (front.left != null) {
                queue.offer(front.left);
            }
            if (front.right != null) {
                queue.offer(front.right);
            }
        }
    }

    public void levelOrder1(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return;
        } else {
            queue.offer(root);
        }
        while (!queue.isEmpty()) {
            TreeNode front = queue.poll();
            if (front.left != null) {
                queue.offer(front.left);
            }
            if (front.right != null) {
                queue.offer(front.right);
            }
            System.out.print(front.val + " ");
        }
    }

    // 判断一棵树是不是完全二叉树
    public boolean isCompleteTree(TreeNode root) {
        if (root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        //将节点放入队列中
        queue.offer(root);
        //先将所有得节点放入队列中
        while (!queue.isEmpty()) {
            //记录弹出得队顶元素
            TreeNode cur = queue.poll();
            // 弹出得元素不为空 且对顶元素不为空
            if (cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                break;
            }
        }

        // 弹出所有队列元素 并观察队列剩余元素
        while (!queue.isEmpty()) {
            TreeNode pop = queue.poll();
            //弹出队列元素
            if (pop != null) {
                return false;
            }
        }
        return true;
    }

    public List<List<Character>> levelOrder2(TreeNode root) {
        List<List<Character>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        // 利用队列 先进先出层序遍历每一层
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            // 记录每一层
            ArrayList<Character> row = new ArrayList<Character>();
            int n = queue.size();
            // 根先进 每层有多少个节点 队列大小就是多大
            for (int i = 0; i < n; i++) {
                // 记录当前节点
                TreeNode cur = queue.poll();
                // 当前节点添加到当前层
                row.add(cur.val);
                // 判断左右子树节点
                if (cur.left != null) {
                    // 入队列
                    queue.add(cur.left);
                }
                if (cur.right != null) {
                    queue.add(cur.right);
                }
            }
            // 将当前得每一层加入总得列表中
            res.add(row);
        }

        return res;
    }

    public void inorder(TreeNode root) {
        if (root == null) {
            return;
        }
        inorder(root.left);
        System.out.print(root.val + " ");
        inorder(root.right);
    }

    public int i = 0;

    // 创建一个树
    public TreeNode createTree(String str) {
        // 遍历字符 将每个字符创建
        TreeNode root = null;
        if (str.charAt(i++) != '#') {
            root = new TreeNode(str.charAt(i)); // 创建根
            root.left = createTree(str);   // 创建根得左树
            root.right = createTree(str); //  创建根得右树
        } else {
            i++;
        }
        return root;
    }




    //public int preIndex ;

    /**
     * 前序中序创建二叉树
     *
     * @param preorder  前序遍历
     * @param inorder   中序遍历
     * @return 返回根节点
     */

/*    public TreeNode buildTree(int [] preorder, int[] inorder) {

        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }

    private TreeNode buildTreeChild(int[] preorder, int[] inorder,int inbegin,int inend) {
        //1、当前根节点是不是还有左子树 或者  右子树
        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode((char) preorder[preIndex]);
        //2. 找到root再中序遍历的位置
        int rootIndex = findIndex(inorder,inbegin,inend,preorder[preIndex]);
        preIndex++;
        if(rootIndex == -1) {
            return null;
        }
        //3、构建左子树和右子树
        root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
        root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);
        return root;
    }

    private int findIndex (int[] inorder,int inbegin,int inend,int val) {
        for(int i = inbegin;i <= inend;i++) {
            if(inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }*/



    /*    Map<Integer, Integer> map;

     */
    /**
     * @param inorder
     * @param postorder 后续
     * @return
     *//*
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i); // 将中序遍历的值存储在map中便于寻找对应位置
        }

        return buildTreeChild(postorder, 0, postorder.length, inorder, 0, inorder.length);
    }

    // 分割数组采取左闭右开原则
    private TreeNode buildTreeChild(int[] postorder, int leftlen1, int rightlen1,
                                    int[] inorder, int leftlen2, int rightlen2) {
        if (leftlen2 >= rightlen2 || leftlen1 >= rightlen1) {
            return null;
        }
        // 1. 根据后续遍历在中序中的位置确定根节点
        int rootIndex = map.get(postorder[rightlen1 - 1]);
        TreeNode root = new TreeNode((char) inorder[rootIndex]); // 确立中序遍历的根节点 -- 构造节点
        // 记录中序遍历中根节点左子树长度
        int leftTree = rootIndex - leftlen2;
        // 2 .构造左树
        root.left = buildTreeChild(postorder, leftlen1, leftlen1 + leftTree, inorder, leftlen2, rootIndex);
        root.right = buildTreeChild(postorder, leftlen1 + leftTree, rightlen1 - 1, inorder, rootIndex + 1, rightlen2);
        return root;

    }*/



    public int postIndex = 0;

    /**
     * 根据前序中序遍历思路解决中序后序遍历创建二叉树
     *
     * @param inorder   中序遍历
     * @param postorder 后续遍历
     * @return 根节点
     */
    public TreeNode buildTree(int[] inorder, int[] postorder) {

        postIndex = postorder.length - 1;
        return buildTreeChild(postorder, inorder, 0, inorder.length - 1);
    }

    private TreeNode buildTreeChild(int[] postorder, int[] inorder, int inbegin, int inend) {
        //1、当前根节点是不是还有左子树 或者  右子树
        if (inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode((char) postorder[postIndex]);
        //2. 找到root再中序遍历的位置
        int rootIndex = findIndex(inorder, inbegin, inend, postorder[postIndex]);
        postIndex--;
        if (rootIndex == -1) {
            return null;
        }
        //3、构建左子树和右子树
        // 根据分割中序之后的情况只能先构建右子树！！！
        root.right = buildTreeChild(postorder, inorder, rootIndex + 1, inend);

        root.left = buildTreeChild(postorder, inorder, inbegin, rootIndex - 1);

        return root;
    }

    private int findIndex(int[] inorder, int inbegin, int inend, int val) {
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == val) {
                return i;
            }
        }
        return -1;

    }


    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        treeChild(root, stringBuilder);
        return stringBuilder.toString(); //转换为String类型
    }

    /**
     * 根据前序遍历创建字符（”（）“）二叉树
     * @param root 根节点
     * @param stringBuilder 拼接
     */
    private void treeChild(TreeNode root, StringBuilder stringBuilder) {
        if (root == null) {
            return;
        }
        stringBuilder.append(root.val);
        if (root.left != null) {
            stringBuilder.append("(");
            treeChild(root.left, stringBuilder);
            stringBuilder.append(")");
        } else {
            if (root.right == null) {
                return;
            } else {
                stringBuilder.append("()");
            }
        }

        if (root.right == null) {
            return;
        } else {
            stringBuilder.append("(");
            treeChild(root.right, stringBuilder);
            stringBuilder.append(")");
        }

    }


}
